package com.example.base.adapter

import androidx.annotation.LayoutRes
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.base.adapter.holder.RVHolder

/**
 *  基于生命周期感知的adapter基类
 *  可以使用liveData
 *
 *  需要使用into来绑定recyclerView!!
 */
open class LifecycleAdapter<T, VH : RVHolder>(@LayoutRes layoutId: Int) : XAdapter<T, VH>(layoutId),
    LifecycleEventObserver,
    LifecycleOwner {

    private var recyclerView: RecyclerView? = null

    /** 获取Lifecycle的接口，在 into 方法实现*/
    lateinit var getLifecycleAction: (() -> Lifecycle)

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (event == Lifecycle.Event.ON_DESTROY) {
            this.recyclerView?.adapter = null
            source.lifecycle.removeObserver(this)
        }
    }

    override fun getLifecycle(): Lifecycle {
        return getLifecycleAction.invoke()
    }
}

fun <T, VH : RVHolder> LifecycleAdapter<T, VH>.into(
    recyclerView: RecyclerView,
    layoutManager: RecyclerView.LayoutManager? = null
) = apply {
    val context = recyclerView.context
    recyclerView.layoutManager = layoutManager ?: LinearLayoutManager(context)
    recyclerView.adapter = this
    if (context is LifecycleOwner) {
        context.lifecycle.addObserver(this)
        getLifecycleAction = { context.lifecycle }
    }
}

